package cn.wn.mapper;

import cn.wn.pojo.Permission;
import cn.wn.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface PermissionMapper {

    /**
     * 根据用户id查询权限
     */
    @Select("SELECT\n" +
            "            DISTINCT p.*\n" +
            "            FROM wn_permission p\n" +
            "              INNER JOIN wn_role_permission rp ON p.pid=rp.permission_id\n" +
            "              INNER JOIN wn_role_user ru ON ru.role_id=rp.role_id\n" +
            "            WHERE 1=1\n" +
            "            AND ru.user_id=#{userId}")
    List<Permission> findPermissionByUserId(Integer userId);

    /**
     * 查询所有权限
     * @return
     */
    @Select("SELECT * FROM wn_permission")
    List<Permission> findAll();

    /**
     *  查询角色的权限
     * @param roleId
     * @return
     */
    @Select("SELECT p.* FROM wn_permission p " +
            "INNER JOIN wn_role_permission rp ON p.pid=rp.permission_id WHERE role_id=#{roleId}")
    List<Permission> findRolePermission(Integer roleId);

    /**
     * 根据角色id删除角色权限中间表数据
     */
    @Delete("DELETE FROM wn_role_permission WHERE role_id=#{roleId}")
    void deleteRolePermissionByRoleId(Integer roleId);

    /**
     * 当用户减少了角色的权限后，数据库要删除角色权限关系。
     */
    void deleteNotExists(
            @Param("roleId") Integer roleId,
            @Param("permissions") Integer[] permissions);

    /**
     * 根据角色id、权限id查询角色权限中间表
     */
    @Select("SELECT COUNT(*) FROM wn_role_permission WHERE role_id=#{rid} AND permission_id=#{pid}")
    Long countRolePermission(
            @Param("rid") Integer roleId,
            @Param("pid") Integer permission);

    /**
     * 给角色添加权限
     */
    @Insert("insert into wn_role_permission(role_id,permission_id) values (#{rid},#{pid})")
    void saveRolePermission(
            @Param("rid") Integer roleId,
            @Param("pid") Integer permission);

}
